﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Text;
using FreeDAM.Domain.Abstract;
using FreeDAM.Domain.Entities;

namespace FreeDAM.Domain.Concrete
{
    public class EfRepositoryBase<T> : IRepository<T> where T : EntityBase
    {
        private EfDbContext _DbContext;
        private readonly IDbSet<T> DbSet;

        protected IDatabaseFactory DatabaseFactory { get; private set; }

        protected EfDbContext DbContext
        {
            get
            {
                return _DbContext ?? (_DbContext = DatabaseFactory.Get());
            }
        }

        public EfRepositoryBase(IDatabaseFactory databaseFactory)
        {
            DatabaseFactory = databaseFactory;
            DbSet = DbContext.Set<T>();
        }

        public IQueryable<T> All
        {
            get
            {
                return DbSet.AsQueryable();
            }
        }

        public T Find(int id)
        {
            return DbSet.Find(id);
        }

        public void InsertOrUpdate(T entity)
        {
            if (entity.Id == default(int))
            {
                DbSet.Add(entity);
            }
            else
            {
                DbSet.Attach(entity);
                DbContext.Entry(entity).State = EntityState.Modified;
            }
        }

        public void Delete(int id)
        {
            T entity = DbSet.Find(id);
            DbSet.Remove(entity);
        }

        public void Save()
        {
            DbContext.SaveChanges();
        }
    }
}
